package com.itheima.springbootsecurity.controller;

import com.itheima.springbootsecurity.domain.Result;
import com.itheima.springbootsecurity.domain.User;
import com.itheima.springbootsecurity.exception.CustomAuthenticationException;
import com.itheima.springbootsecurity.service.UserService;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    private UserService userService;

    @PostMapping("/login")
    public Result login(@RequestBody User user) {

        String token = userService.login(user);
        if (StringUtils.hasLength(token)) {
            return Result.success(token);
        } else {
            return Result.error("登录失败");
        }
    }

    @PostMapping("/logout")
    public Result logout(HttpServletRequest request, HttpServletResponse response) {
        if (userService.logout(request, response)) {
            return Result.success();
        }else {
            return Result.error("退出失败");
        }
    }

    @PostMapping("/exceptiontest")
    private Result exceptionTest() {
        throw new CustomAuthenticationException("测试抛出异常的情况");
//        return Result.success("exceptiontest");
    }
}
